let logger = require("pomelo-logger").getLogger(__filename);
let pomelo = require("pomelo");
let COMPONENT_NAME = "gameComponent";

exports.create = function (owner) {
    return new Component(owner);
};

let Component = function (owner) {
    this.owner = owner;
    this.game = null;
};

Component.prototype.join = function (game) {
    this.game = game;
};

Component.prototype.leave = function () {
    this.game = null;
};

Component.prototype.toJSON = function () {
    return {
        gid: this.getGameId()
    };
};

Component.prototype.getGame = function () {
    return this.game;
};

Component.prototype.getGameId = function () {
    return this.game != null ? this.game.getGid() : 0;
};

Component.prototype.fromBSON = function (document) {
    if (!document.hasOwnProperty(COMPONENT_NAME)) {
        logger.error("load gameComponent failed. document=" + JSON.stringify(document));
        this.game = null;
        return;
    }
    let node = document[COMPONENT_NAME];
    let gameService = pomelo.app.get("gameService");
    this.game = gameService.getGameById(node.gid);
};

Component.prototype.buildBSON = function (document) {
    document[COMPONENT_NAME] = {
        gid: this.getGameId()
    };
};